package com.framework.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/5/3 21:05
 * @since JDK 1.8
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    /** spring上下文 */
    private static ApplicationContext context;

    /**
     * @see ApplicationContextAware#setApplicationContext(ApplicationContext)
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.context = applicationContext;
    }

    /**
     * @return
     */
    public static ApplicationContext getContext() {
        return context;
    }

    /**
     * @param beanName
     * @return
     */
    public final static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    /**
     * @param beanName
     * @param requiredType
     * @return
     */
    public final static Object getBean(String beanName, Class<?> requiredType) {
        return context.getBean(beanName, requiredType);
    }

    /**
     * @param beanType
     * @return
     */
    public final static <T> T getBean(Class<T> beanType) {
        return context.getBean(beanType);
    }
}
